package Persistent;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import domain.Forum;
import domain.Post;
import domain.user.User;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FileInputStream in = null;
		FileOutputStream out = null;
		
		try {			
			
			JAXBContext jc = JAXBContext.newInstance("Persistent");
			Unmarshaller u = jc.createUnmarshaller();
			
			in = new FileInputStream("taltalim.xml");
			
			// Obtain the data from the XML file. 						 
			XmlForum forum = (XmlForum)u.unmarshal(in);			
			in.close();	
			System.out.println(forum);
			
		//	System.out.println(forum.getForumName());
			
			// Create a factory.
			ObjectFactory factory = new ObjectFactory();

			//XmlForum forum = factory.createXmlForum();
			
			//create a new user
			XmlLoggedOnUser user1 = factory.createXmlLoggedOnUser();
			user1.setFName("yakov"+(int)(Math.random() * 1000.0));
			user1.setLName("yarmoloy"+(int)(Math.random() * 1000.0));
			user1.setPassword("gader"+(int)(Math.random() * 1000.0));
			user1.setSignature("ha'smolan"+(int)(Math.random() * 1000.0));
			user1.setUserName("yarmoloy"+(int)(Math.random() * 1000.0));
			user1.setEMail("y@gmail"+(int)(Math.random() * 1000.0)+"."+"com");
			
			//add the user to the userList of the forum
			(forum.getUsers()).add(user1);
			
			//create a new post and link it to the user
			XmlPost post1 = factory.createXmlPost();
			post1.setSubject("subject"+(int)(Math.random() * 1000.0));
			post1.setOwner(user1);
			post1.setPostId((int)(Math.random() * 1000.0));
			post1.setBody("body"+(int)(Math.random() * 1000.0));
			(forum.getPosts()).add(post1);
			
			Marshaller m = jc.createMarshaller();	
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			
			// Write all the data back to the XML file.
			out = new FileOutputStream("taltalim.xml");
			m.marshal(forum,out);
			out.close();
			
		} catch (JAXBException e) {			
			e.printStackTrace();		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 				
		finally {			
			System.exit(0);
		}
	}

}
